package progress.exa29_3.ui;

import progress.exa29_3.StudentAddress;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class StudentClient extends Application {
    private TextField tfName=new TextField();
    private TextField tfStreet=new TextField();
    private TextField  tfCity=new TextField();
    private TextField tfState=new TextField();
    private TextField tfZip=new TextField();

    private Button btRegister=new Button("发送数据到服务器");
    String host="localhost";//定义ip地址

    public void start(Stage primaryStage) {
        GridPane pane=new GridPane();
        pane.add(new Label("姓名"),0,0);
        pane.add(tfName,1,0);
        pane.add(new Label("街道"),0,1);
        pane.add(tfStreet,1,1);
        pane.add(new Label("城市"),0,2);
        HBox hBox=new HBox(2);
        pane.add(hBox,1,2);
        hBox.getChildren().addAll(tfCity,new Label("州"),tfState,new Label("编码"),tfZip);
        pane.add(btRegister,1,3);
        GridPane.setHalignment(btRegister, HPos.RIGHT);

        pane.setAlignment(Pos.CENTER);
        tfName.setPrefColumnCount(15);
        tfStreet.setPrefColumnCount(15);
        tfCity.setPrefColumnCount(10);
        tfState.setPrefColumnCount(2);
        tfZip.setPrefColumnCount(3);
        btRegister.setOnAction(new ButtonListerner());

        Scene scene=new Scene(pane,450,200);
        primaryStage.setTitle("StudentClient");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private class ButtonListerner implements EventHandler<ActionEvent> {

        public void handle(ActionEvent e)
        {
            try{
                Socket socket=new Socket(host,8001);//定义套接字的ip和端口号

                //定义套接字的对象输出流
                ObjectOutputStream toServer=new ObjectOutputStream(socket.getOutputStream());

                String name=tfName.getText().trim();
                String street=tfStreet.getText().trim();
                String city=tfCity.getText().trim();
                String state=tfState.getText().trim();
                String zip=tfZip.getText().trim();

                StudentAddress s=new StudentAddress(name,street,city,state,zip);
                //向对象输出流写入对象
                toServer.writeObject(s);
            }catch(IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}